package query;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;

import metrics.NormalizedPRStatictic;
import metrics.PRStatistic;
import metrics.RecallGraph;
import metrics.PrRcGraph;

import org.jfree.ui.RefineryUtilities;

import document.InvertedIndex;

public class VectorQueryLibrary extends QueryLibrary
{
	public NormalizedPRStatictic getStatistics() {
		//normalize all statistics
		Vector<NormalizedPRStatictic> allNormalized = new Vector<NormalizedPRStatictic>();
		for (PRStatistic statistic : queryStatistics) {
			//System.out.println("Query ");
			//statistic.showStatistics();
			//statistic.getNormalizedVersion().showStatistics();
			allNormalized.add(statistic.getNormalizedVersion());
		}
		
		//Compute the Average
		NormalizedPRStatictic summary = new NormalizedPRStatictic();
		for(int i =0; i<=NormalizedPRStatictic.NORMALIZAION_PRECISION; i++) {
			float sum = 0;
			for (NormalizedPRStatictic statictic : allNormalized) {
				sum += statictic.getPrecisionOfEntry(i);
			}
			summary.addEntry((float)i/NormalizedPRStatictic.NORMALIZAION_PRECISION, sum/(float)allNormalized.size());
		}
		summary.showStatistics();

		return summary;
	
	}
	
	@Override
	protected void buildQuery(String content)
	{
		VectorTerm query = new VectorTerm(content);
		queries.add(query);
	}
	
	@Override
	public void processAll(InvertedIndex index) 
	{
		queryStatistics = new Vector<PRStatistic>();
		buildResults();
		
		for(int i=0; i<queries.size(); i++)
		{
			queries.get(i).process(index);
			PRStatistic statistics = new PRStatistic();
			Vector<String>  computedResults = index.toDocNames(queries.get(i).getResult());
			double recall = 0;
			int j =0;
			int hits = 0;
			boolean exclude = false;
			while(recall < 0.9999999999 && j < computedResults.size())
			{
				if(has(computedResults.get(j),results.get(i)))
				{
					hits++;
					recall += 1/((double)results.get(i).size());
				}
				j++;
				if(j==1 && hits != 1)
				{
					exclude = true;
				}
				statistics.addEntry((float)recall, ((float)hits)/((float)j));
			}
			//if(!exclude)
			{
				queryStatistics.add(statistics);
			}
			System.out.println("Query "+i+" : Recall = "+recall+"  Precision  = "+((double)hits)/((double)j));
		}
	}
	
	public void processAllRelevance(InvertedIndex index, double weightOldQuery, double weightRelevant, double weightIrrelevant) {
		queryStatistics = new Vector<PRStatistic>();
		buildResults();
		
		for(int i=0; i<queries.size(); i++)
		{
			VectorTerm term = (VectorTerm)queries.get(i);
			term.processWithRelevanceFeedback(index, weightOldQuery, weightRelevant, weightIrrelevant);
			PRStatistic statistics = new PRStatistic();
			Vector<String>  computedResults = index.toDocNames(queries.get(i).getResult());
			double recall = 0;
			int j =0;
			int hits = 0;
			boolean exclude = false;
			while(recall < 0.9999999999 && j < computedResults.size())
			{
				if(has(computedResults.get(j),results.get(i)))
				{
					hits++;
					recall += 1/((double)results.get(i).size());
				}
				j++;
				if(j==1 && hits != 1)
				{
					//System.out.print("Query number "+i+"\n");
					exclude = true;
				}
				statistics.addEntry((float)recall, ((float)hits)/((float)j));
			}
			//if(!exclude)
			{
				queryStatistics.add(statistics);
			}
			
			//System.out.println("Query "+i+" : Recall = "+recall+"  Precision  = "+((double)hits)/((double)j));
		}
		
	}

	
	protected boolean has(String s, Vector<String> in)
	{
		for(String i : in)
		{
			if(s.compareTo(i) == 0)
			{
				return true; // sorry for this :-)
			}
		}
		return false;
	}
	
	protected void buildResults()
	{
		results = new Vector<Vector<String>>();
		String whitStr = "^([\\s.,;:\\-\\(\\)\\!\\?'\"])+$";
		BufferedReader reader = null;
		String line = "";
		try {
			reader = new BufferedReader(new FileReader(RELEVANCY_LIST));
			while ((line = reader.readLine()) != null)
			{
				if(!line.matches(whitStr) && line.length() > 0)
				{
					Vector<String> result = new Vector<String>();
					String [] tokens = line.split("[\\s.,;:\\-\\(\\)\\!\\?'\"]");
					for(int i=1; i<tokens.length; i++)		// skip first element
					{
						if(!tokens[i].matches(whitStr) && tokens[i].length() > 0)
						{
							result.add("doc"+tokens[i]);
						}
					}
					results.add(result);
				}
			}
			reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private Vector<PRStatistic> queryStatistics;
	private Vector<Vector<String>> results;
	//private final String RELEVANCY_LIST = "TIME/Test_Answer" + File.separator + "RelevancyLists.txt";
	private final String RELEVANCY_LIST = "TIME" + File.separator + "RelevancyLists.txt";

	

}
